using System;
using System.Collections.Generic;
using ShangHeng.HardwareSDK.Interface;
using System.Windows.Forms;

namespace ShangHeng.HardwareSDK.CardReader
{
	internal class ZKUHFReaderCore : ICardReader
	{
		private ZKUHFReader zkUHFReader2;

		private string IPaddr;

		private int Port;

		private bool Connected = false;

		public ZKUHFReaderCore(string _IPaddr, int _port)
		{
			IPaddr = _IPaddr;
			Port = _port;
			zkUHFReader2 = new ZKUHFReader();
		}

		public bool GetConnectStatus()
		{
			return Connected;
		}

		public bool Open()
		{
			try
			{
				byte ComAddr = 0;
				ComAddr = Convert.ToByte("FF", 16);
				int result = zkUHFReader2.OpenNetPort(IPaddr, Port, ref ComAddr);
				Connected = result == 0;
				return Connected;
			}
			catch (Exception ex)
			{
				Connected = false;
				MessageBox.Show("【Zk读卡器Open】" + ex);
				return false;
			}
		}

		public bool Close()
		{
			try
			{
				Connected = false;
				int result = zkUHFReader2.CloseNetPort();
				return result == 0;
			}
			catch (Exception ex)
			{
				Connected = false;
                MessageBox.Show("【Zk读卡器Close】" + ex);
				return false;
			}
		}

		public bool ReConnect()
		{
			Close();
			return Open();
		}

		public List<string> GetEpcNOs()
		{
			try
			{
				if (!Connected)
				{
					ReConnect();
				}
				if (Connected)
				{
					byte ComAddr = 0;
					zkUHFReader2.Inventory_G2(ref ComAddr, 0, 0, 0);
					return zkUHFReader2.EPCIDs;
				}
                MessageBox.Show("【Zk读卡器GetEpcNOs】读卡器连接失败");
				return null;
			}
			catch (Exception ex)
			{
				Connected = false;
                MessageBox.Show("【Zk读卡器GetEpcNOs】" + ex);
				return null;
			}
		}

		public string GetEpc()
		{
			List<string> epcs = GetEpcNOs();
			if (epcs != null && epcs.Count > 0)
			{
				return epcs[epcs.Count - 1];
			}
			return null;
		}

		public void Clear()
		{
		}
	}
}
